EventBus 3.1.1 源码分析
EventBus 是一个事件总线框架,解决了组件之间通信的问题。使用了观察者模式。使代码更加简洁
简单使用
1.引入依赖compile 'org.greenrobot:eventbus:3.1.1'
2.定义事件1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22public class MessageEvent {
private Object msg;
public MessageEvent(Object msg) {
this.msg = msg;
}
public Object getMsg() {
return msg;
}
public void setMsg(Object msg) {
this.msg = msg;
}
public String toString() {
return "MessageEvent{" +
"msg=" + msg +
'}';
}
}
3.注册与反注册1
2
3
4
5
6
7
8
9
10
11
12
13
14
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EventBus.getDefault().register(this);
mTextView = findViewById(R.id.tv);
}
protected void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}
4.在某个地方发送事件1
EventBus.getDefault().post(new MessageEvent("嘿嘿嘿"));
5.在注册页面接收事件1
2
3
4
5
6
7
8
9
10
11100, sticky = false) (threadMode = ThreadMode.MAIN, priority =
public void onMessageEventPost(MessageEvent messageEvent) {
Log.e(TAG, "onMessageEventPost: " + messageEvent.getMsg().toString());
mTextView.setText(messageEvent.getMsg().toString());
}
150, sticky = false) (threadMode = ThreadMode.MAIN, priority =
public void onMessageEvent(MessageEvent messageEvent) {
Log.e(TAG, "onMessageEvent: " + messageEvent.getMsg().toString());
mTextView.setText(messageEvent.getMsg().toString());
}
注册分析
EventBus.getDefault().register(this);
这行代码都做了什么呢,大眼一看感觉好像是用的单例模式构造对象。
创建EventBus对象1
2
3
4
5
6
7
8
9
10
11
12/** Convenience singleton for apps using a process-wide EventBus instance. */
/*使用双重锁校验创建EventBus对象*/
public static EventBus getDefault() {
if (defaultInstance == null) {
synchronized (EventBus.class) {
if (defaultInstance == null) {
defaultInstance = new EventBus();
}
}
}
return defaultInstance;
}
注册1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24/**
* Registers the given subscriber to receive events. Subscribers must call {@link #unregister(Object)} once they
* are no longer interested in receiving events.
* 参数类型是Object,可以接收各种类型。
* <p/>
* Subscribers have event handling methods that must be annotated by {@link Subscribe}.
* The {@link Subscribe} annotation also allows configuration like {@link
* ThreadMode} and priority.
*/
public void register(Object subscriber) {
// 使用反射获取到类的字节码文件
Class<?> subscriberClass = subscriber.getClass();
// 通过反射获取该类中所有 包含 @Subscribe 注解的方法,得到的是一个集合
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
// 上锁
synchronized (this) {
// 循环遍历所有的方法,进行订阅
for (SubscriberMethod subscriberMethod : subscriberMethods) {
// 订阅 subscriber 在这里表示就是MainActivity
// subscriberMethod 在这里表示方法有两个 onMessageEventPost onMessageEvent
subscribe(subscriber, subscriberMethod);
}
}
}
来到了SubscriberMethodFinder
类中,从类名直接来看,是订阅者方法搜寻者,通过类的字节码文件找到所有订阅者的方法,这个类是在Eventbus的构造方法中创建的。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
private static final Map<Class<?>, List<SubscriberMethod>> METHOD_CACHE = new ConcurrentHashMap<>();
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
// 这里使用Map做了一个缓存,先从Map中找,如果没有在通过反射去遍历寻找。能提高效率
List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
// 如果Map中存在,就直接取出来
if (subscriberMethods != null) {
return subscriberMethods;
}
//ignoreGenerateIndex这个值表示是否忽略注解器生成的MyEventBusIndex
// 这个值默认是false,表示可以通过EventBusHandler来设置他的值
if (ignoreGeneratedIndex) {
// 利用反射来获取订阅类中所有的订阅方法信息
subscriberMethods = findUsingReflection(subscriberClass);
} else {
// 第一次走到这里 从注解器生成的MyEventBusIndex类中获得订阅类的订阅方法信息
subscriberMethods = findUsingInfo(subscriberClass);
}
if (subscriberMethods.isEmpty()) {
throw new EventBusException("Subscriber " + subscriberClass
+ " and its super classes have no public methods with the @Subscribe annotation");
} else {
METHOD_CACHE.put(subscriberClass, subscriberMethods);
return subscriberMethods;
}
}
1 | private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) { |
通过反射获取订阅类中的订阅方法信息1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47private void findUsingReflectionInSingleClass(FindState findState) {
Method[] methods;
try {
// This is faster than getMethods, especially when subscribers are fat classes like Activities
// 反射获取类中所有的方法
methods = findState.clazz.getDeclaredMethods();
} catch (Throwable th) {
// Workaround for java.lang.NoClassDefFoundError, see https://github.com/greenrobot/EventBus/issues/149
methods = findState.clazz.getMethods();
findState.skipSuperClasses = true;
}
// 循环遍历
for (Method method : methods) {
// 拿到方法的修饰符
int modifiers = method.getModifiers();
// 方法只能是 public ,如果设置成private 和 static abstract 的话将会报错
if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
// 拿到参数类型信息
Class<?>[] parameterTypes = method.getParameterTypes();
// 只允许包含一个参数
if (parameterTypes.length == 1) {
// 拿到方法上的注解信息
Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
if (subscribeAnnotation != null) {
// 如果注解不为空,就获取注解当中的参数事件类型
Class<?> eventType = parameterTypes[0];
// 检测添加
if (findState.checkAdd(method, eventType)) {
// 获取 threadMode
ThreadMode threadMode = subscribeAnnotation.threadMode();
// 向集合里面添加,解析方法注解的所有属性
findState.subscriberMethods.add(new SubscriberMethod(method, eventType, threadMode,
subscribeAnnotation.priority(), subscribeAnnotation.sticky()));
}
}
} else if (strictMethodVerification && method.isAnnotationPresent(Subscribe.class)) {
String methodName = method.getDeclaringClass().getName() + "." + method.getName();
throw new EventBusException("@Subscribe method " + methodName +
"must have exactly 1 parameter but has " + parameterTypes.length);
}
} else if (strictMethodVerification && method.isAnnotationPresent(Subscribe.class)) {
String methodName = method.getDeclaringClass().getName() + "." + method.getName();
throw new EventBusException(methodName +
" is a illegal @Subscribe method: must be public, non-static, and non-abstract");
}
}
}
当我们获取到所有的标有 @subscribe 注解的方法之后,就要开始进行订阅subscribe 操作,主要做的工作就是解析所有 subscriberMethod 的eventType,然后解析成Map<Class<?>, CopyOnWriteArrayList
1 |
|
Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType
这个Map的数据结构,subscriber -> MainActivity, subscriberMehtod -> onMessageEventPost
粘性事件(sticky event):普通事件是先注册,然后发送事件才能收到;而粘性事件,在发送事件之后再订阅该事件也能收到。此外,粘性事件会保存在内存中,每次进入都会去内存中查找获取最新的粘性事件,除非你手动解除注册。
post()发送分析
EventBus.getDefault().post(new MessageEvent("嘿嘿嘿"));
1 | // ThreadLocal 是一个创建线程局部变量的类,,通常情况下我们创建的变量是可以被任何一个线程访问的,但是ThreadLocal创建的变量只能被当前线程访问,其他 |
发送事件
1 | private void postSingleEvent(Object event, PostingThreadState postingState) throws Error { |
BACKGROUND 与 ASYNC 的区别:
前者中的任务是串行调用,后者是异步调用。
总结:
事件的发送和接收,主要是通过subscriptionsByEventType这个列表,Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType
。我们将订阅即接收事件的方法存储在这个列表,发布事件的时候在遍历列表,查询出相对应的方法并通过反射执行。